'use strict';

const Controller = require('egg').Controller;

class MomentController extends Controller {
  async create() {
    const currentid = this.ctx.authUser.id;
    this.ctx.validate({
      content: {
        type: "string",
        required: true,
        desc: "朋友圈内容",
      },
      image: {
        type: "string",
        required: false,
        desc: "朋友圈图片",
      },
      video: {
        type: "string",
        required: false,
        desc: "朋友圈视频",
      },
      location: {
        type: "string",
        required: false,
        desc: "位置",
      },
      remind: {
        type: "string",
        required: false,
        desc: "提醒谁看",
      },
      see: {
        type: "string",
        required: false,
        defValue: "all",
        desc: "谁可以看 all公开 none私密",
      },
      type: {
        type: "string",
        required: true,
        range: {
          in: ["content", "image", "video"]
        },
        desc: "谁可以看 all公开 none私密",
      },

    })
    let moment = await this.app.model.Moment.create({
      content: this.ctx.request.body.content,
      image: this.ctx.request.body.image,
      video: this.ctx.request.body.video,
      location: this.ctx.request.body.location,
      remind: this.ctx.request.body.remind,
      see: this.ctx.request.body.see,
      type: this.ctx.request.body.type,
      user_id: currentid
    })
    if (!moment) {
      this.ctx.apiFail("发送失败")
    }
    this.timeline(moment)
    this.ctx.apiSuccess("发送成功")
  }
  async timeline(moment) {
    console.log(moment, "momentsee")
    const currentid = this.ctx.authUser.id;
    let friends = await this.app.model.Friend.findAll({
      where: {
        user_id: currentid,
        isblack: 0
      },
      attributes: ['friend_id']
    });
    console.log(moment.see, "moment.see")

    let see = moment.see.split(":");
    console.log(see, "see")
    let o = {
      only: [],
      except: []
    }
    let otype = see[0];
    if ((see[0] === 'only' || see[0] === 'except') && see[1]) {
      o[see[0]] = (see[1].split(',')).map(v => parseInt(v));
    }
    let alldata = friends.filter(item => {
      return otype == 'all' || (otype == 'only' && o.only.includes(item.friend_id)) || (otype == 'except' && o.except.includes(item.friend_id))
    })
    alldata = alldata.map(item => {
      return {
        user_id: item.friend_id,
        moment_id: moment.id,
        own: 0
      }
    })
    alldata.push({
      user_id: currentid,
      moment_id: moment.id,
      own: 1

    })
    await this.app.model.MomentTimeline.bulkCreate(alldata);
    let message = {
      avatar: this.ctx.authUser.avatar,
      user_id: currentid,
      type: 'new'
    }
    alldata.forEach(el => {
      let socket = null;
      if (this.app.ws.user) {
        socket = this.app.ws.user[el.user_id];

      }
      //验证对方是否在线

      if (!socket) {
        console.log(123333, "343331")
        this.service.cache.setList("getmessage_" + el.user_id, message)

      } else {
        console.log(123333, "34333")
        //消息推送
        socket.send(JSON.stringify({
          msg: "moment",
          data: message
        }))
        //存到历史记录
        this.service.cache.setList(`chatlog_${el.user_id}_user_${currentuserid}`, message);


      }
      //存储到自己的聊天记录
      this.service.cache.setList(`chatlog_${currentuserid}_user_${el.user_id}`, message);
    })
  }
  async like() {
    let currentid = this.ctx.authUser.id;
    this.ctx.validate({
      id: {
        type: "int",
        required: true,
        desc: "朋友圈id",
      },
    })
    let res = await this.app.model.MomentTimeline.findOne({
      where: {
        user_id: currentid,
        moment_id: this.ctx.request.body.id
      },
      include: [{
        model: this.app.model.Moment,
        attributes: ["user_id"],
        include: [{
          model: this.app.model.MomentLike,
          attributes: ["user_id"],
        }]
      }]
    })
    console.log(res, "momentres")
    if (!res) {
      this.ctx.apiFail("该朋友圈消息不存在")
    }
    let ress = await this.app.model.MomentLike.findOne({
      where: {
        user_id: currentid,
        moment_id: this.ctx.request.body.id
      }
    })
    if (ress) {
      await ress.destroy()
      this.ctx.apiSuccess("取消点赞成功")
    } else {
      await this.app.model.MomentLike.create({
        user_id: currentid,
        moment_id: this.ctx.request.body.id

      })
      this.ctx.apiSuccess("点赞成功")

    }
    let message = {
      avatar: this.ctx.authUser.avatar,
      id: currentid,
      name:this.ctx.authUser.nickname?this.ctx.authUser.nickname:this.ctx.authUser.username,
      type: "like"
    }
    let socket = null;
    if (this.app.ws.user) {
      socket = this.app.ws.user[res.moment.user_id];

    }
    //验证对方是否在线

    if (!socket) {
      console.log(123333, "343331")
      this.service.cache.setList("getmessage_" + res.moment.user_id, message)

    } else {
      console.log(123333, "34333")
      //消息推送
      socket.send(JSON.stringify({
        msg: "moment",
        data: message
      }))
      //存到历史记录
      this.service.cache.setList(`chatlog_${res.moment.user_id}_user_${currentid}`, message);


    }
    //存储到自己的聊天记录
    this.service.cache.setList(`chatlog_${currentid}_user_${res.moment.user_id}`, message);
    if (res.moment.user_id) {
      res.moment.moment_likes.forEach(el => {
        if (el.user_id !== currentid) {
          let socket = null;
          if (this.app.ws.user) {
            socket = this.app.ws.user[el.user_id];

          }
          //验证对方是否在线

          if (!socket) {
            console.log(123333, "343331")
            this.service.cache.setList("getmessage_" + el.user_id, message)

          } else {
            console.log(123333, "34333")
            //消息推送
            socket.send(JSON.stringify({
              msg: "moment",
              data: message
            }))
            //存到历史记录
            this.service.cache.setList(`chatlog_${el.user_id}_user_${currentid}`, message);


          }
          //存储到自己的聊天记录
          this.service.cache.setList(`chatlog_${currentid}_user_${el.user_id}`, message);

        }
      })

    }

  }
  async comment() {
    const currentid = this.ctx.authUser.id
    this.ctx.validate({
      content: {
        type: "string",
        required: true,
        desc: "",
      },
      moment_id: {
        type: "int",
        required: true,
        desc: "",
      },
      reply_id: {
        type: "int",
        required: false,
        desc: "回复id",
      },
    })
    let res = await this.app.model.MomentTimeline.findOne({
      where: {
        user_id: currentid,
        moment_id: this.ctx.request.body.moment_id
      },
      include: [{
        model: this.app.model.Moment,
        attributes: ['user_id'],
        include: [{
          model: this.app.model.MomentLike,
          attributes: ['user_id'],
        }]
      }]
    })
    if (!res) {
      return this.ctx.apiFail("朋友圈消息不存在")
    }
    let ress = await this.app.model.MomentComment.create({
      user_id: currentid,
      moment_id: this.ctx.request.body.moment_id,
      content: this.ctx.request.body.content,
      reply_id: this.ctx.request.body.reply_id
    });
    this.ctx.apiSuccess(ress)
    let message = {
      avatar: this.ctx.authUser.avatar,
      id: currentid,
      name:this.ctx.authUser.nickname?this.ctx.authUser.nickname:this.ctx.authUser.username,
      type: "comment"
    }
    if (res.moment.user_id) {
      res.moment.moment_likes.forEach(el => {
        if (el.user_id !== currentid) {
          let socket = null;
          if (this.app.ws.user) {
            socket = this.app.ws.user[el.user_id];

          }
          //验证对方是否在线

          if (!socket) {
            console.log(123333, "343331")
            this.service.cache.setList("getmessage_" + el.user_id, message)

          } else {
            console.log(123333, "34333")
            //消息推送
            socket.send(JSON.stringify({
              msg: "moment",
              data: message
            }))
            //存到历史记录
            this.service.cache.setList(`chatlog_${el.user_id}_user_${currentid}`, message);


          }
          //存储到自己的聊天记录
          this.service.cache.setList(`chatlog_${currentid}_user_${el.user_id}`, message);

        }
      })

    }
    if (this.ctx.request.body.reply_id > 0) {
      let index = res.moment.moment_likes.findIndex(item => {
        return item.user_id === this.ctx.request.body.reply_id
      })
      if (index === -1) {
        let socket = null;
        if (this.app.ws.user) {
          socket = this.app.ws.user[this.ctx.request.body.reply_id];

        }
        //验证对方是否在线

        if (!socket) {
          console.log(123333, "343331")
          this.service.cache.setList("getmessage_" + this.ctx.request.body.reply_id, message)

        } else {
          console.log(123333, "34333")
          //消息推送
          socket.send(JSON.stringify({
            msg: "moment",
            data: message
          }))
          //存到历史记录
          this.service.cache.setList(`chatlog_${this.ctx.request.body.reply_id}_user_${currentid}`, message);


        }
        //存储到自己的聊天记录
        this.service.cache.setList(`chatlog_${currentid}_user_${this.ctx.request.body.reply_id}`, message);

      }

    }

    console.log(res, "res")
  }
  async momentlineList() {
    let currentid = this.ctx.authUser.id;
    let page = this.ctx.params.page ? parseInt(this.ctx.params.page) : 1;
    let limit = this.ctx.params.limit ? parseInt(this.ctx.params.limit) : 10;
    let offset = (page - 1) * limit
    let rows = await this.app.model.MomentTimeline.findAll({
      where: {
        user_id: currentid
      },
      include: [
        // {
        //   model: this.app.model.User,
        //   attributes: ['id', 'nickname', "username", "avatar"]
        // },
        {
          model: this.app.model.Moment,
          include: [{
            model: this.app.model.User,
            attributes: ['id', 'nickname', "username", "avatar"]
          }, {
            model: this.app.model.MomentComment,
            attributes: {
              exclude: ['created_at', 'updated_at']
            },
            include: [{
              model: this.app.model.User,
              as: 'momentCommentUser',
              attributes: ['id', 'nickname', "username"]

            }, {
              model: this.app.model.User,
              as: 'momentCommentReply',
              attributes: ['id', 'nickname', "username"]

            }]
          }, {
            model: this.app.model.MomentLike,
            attributes: ['user_id', 'moment_id'],
            include: [{
              model: this.app.model.User,
              attributes: ['id', 'nickname', 'username']
            }]
          }]
        }],
      offset,
      limit,
      order: [
        ['id', "DESC"]
      ]
    })
    let friends = await this.app.model.Friend.findAll({
      where: {
        user_id: currentid
      },
      attributes: ['friend_id']
    })
    friends = friends.map(item => item.friend_id)
    rows = rows.map(item => {
      let comments = [];
      item.moment.moment_comments.forEach(el => {
        if (friends.includes(el.momentCommentUser.id) || el.momentCommentUser.id === currentid) {
          comments.push({
            content: el.content,
            user: {
              id: el.momentCommentUser.id,
              name: el.momentCommentUser.nickname || el.momentCommentUser.username
            },
            reply: el.momentCommentReply ? {
              id: el.momentCommentReply.id,
              name: el.momentCommentReply.nickname || el.momentCommentReply.username

            } : null
          })
        }
      })
      let likes = [];
      item.moment.moment_likes.forEach(el => {
        if (friends.includes(el.user.id) || el.user_id === currentid) {
          likes.push({
            id: el.user.id,
            name: el.user.nickname || el.user.username
          })
        }
      })
      console.log(item, "itemm")
      console.log(item.moment.user, "itemm")
      return {
        user_id: item.user_id,
        user_name: item.moment.user.nickname ? item.moment.user.nickname : item.moment.user.username,
        avatar: item.moment.user.avatar,
        moment_id: item.moment.id,
        content: item.moment.content,
        image: item.moment.image ? item.moment.image.split(',') : [],
        video: item.moment.video ? (item.moment.video) : null,
        location: item.moment.location,
        own: 1,
        created_at: item.created_at,
        comments,
        likes
      }
    })
    this.ctx.apiSuccess(rows)
  }
  async list() {
    let currentid = this.ctx.authUser.id;
    let page = this.ctx.params.page ? parseInt(this.ctx.params.page) : 1;
    let limit = this.ctx.params.limit ? parseInt(this.ctx.params.limit) : 10;
    let offset = (page - 1) * limit
    let rows = await this.app.model.Moment.findAll({
      where: {
        user_id: currentid
      },
      include: [
        {
          model: this.app.model.User,
          attributes: ['id', 'nickname', "username", "avatar"]
        },
        {
          model: this.app.model.MomentComment,
          attributes: {
            exclude: ['created_at', 'updated_at']
          },
          include: [{
            model: this.app.model.User,
            as: 'momentCommentUser',
            attributes: ['id', 'nickname', "username"]

          }, {
            model: this.app.model.User,
            as: 'momentCommentReply',
            attributes: ['id', 'nickname', "username"]

          }]
        }, {
          model: this.app.model.MomentLike,
          attributes: ['user_id', 'moment_id'],
          include: [{
            model: this.app.model.User,
            attributes: ['id', 'nickname', 'username']
          }]
        }],

      offset,
      limit,
      order: [
        ['id', "DESC"]
      ]
    })
    rows = rows.map(item => {
      let comments = item.moment_comments.map(el => {
        return {
          content: el.content,
          user: {
            id: el.momentCommentUser.id,
            name: el.momentCommentUser.nickname || el.momentCommentUser.username
          },
          reply: el.momentCommentReply ? {
            id: el.momentCommentReply.id,
            name: el.momentCommentReply.nickname || el.momentCommentReply.username

          } : null

        }
      })
      let likes = item.moment_likes.map(v => {
        return {
          id: v.user.id,
          name: v.user.nickname || v.user.username
        }
      })
      return {
        user_id: item.user_id,
        user_name: item.user.nickname || item.user.username,
        avatar: item.user.avatar,
        moment_id: item.id,
        content: item.content,
        image: item.image ? item.image.split(',') : [],
        video: item.video ? JSON.parse(item.video) : null,
        location: item.location,
        own: 1,
        created_at: item.created_at,
        comments,
        likes
      }
    })
    this.ctx.apiSuccess(rows)
  }
 
}

module.exports = MomentController;
